'''市场情绪'''
import pathlib
import json
# import datetime
from datetime import datetime
from pyecharts.commons.utils import JsCode
from pyecharts import options as opts
from pyecharts.charts import Line
import config.globalVariable as Gv
import api.xuangubaoApi.XgbApi as xgbAPI

fileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.lineChartfileaddr
line_global = None

from pyecharts.globals import CurrentConfig
default_host = CurrentConfig.ONLINE_HOST
print(default_host)
custom_host = "https://cdnjs.cloudflare.com/ajax/libs/echarts/4.8.0/"
CurrentConfig.ONLINE_HOST = custom_host

colorlist = ['#FF1493','#FF4500','#FF00FF','#DC143C','#FF8C00','#FFD700','#ADFF2F','#1E90FF','#FF69B4','#DA70D6']
colorindex = 0

def datahandler(**kwargs):
    numstr = kwargs.get('numstr')
    plate = kwargs.get('plate')
    openstatus = kwargs.get('openstatus')
    num = 20
    if numstr is not None and len(numstr)>0:
        num = int(numstr)
    # 显示板块下数据
    data = {}
    try:
        jsonfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.jsonfileaddr
        with open(jsonfileaddr, 'r') as f:
            data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")
    if data is None or not len(data):
        return
    #涨跌数据
    hread_data = {}
    try:
        hreadfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.hreadfileaddr
        with open(hreadfileaddr, 'r') as f:
            hread_data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

    if hread_data is None or not len(hread_data):
        return
    # 获取最后5个键和对应的值
    last_five_items = list(reversed(data.items()))[:num]
    hread_last_five_items = list(reversed(hread_data.items()))[:num]

    hread_data_obj={}
    szjslist = []
    xdjslist = []
    for key, value in reversed(hread_last_five_items):
        rise_count = value.get('rise_count')
        szjslist.append(rise_count)
        fall_count = value.get('fall_count')
        xdjslist.append(fall_count)
    hread_data_obj['szjslist'] = szjslist
    hread_data_obj['xdjslist'] = xdjslist
    # 打印结果
    x_axis = []
    y_axis = []
    title_data = []
    code_data = []
    plate_data = []
    plate_title_data = []
    plate_pop_data = []
    second_axis = []
    for key, value in reversed(last_five_items):
        x_axis.append(key)
        lbnum = 0
        secondnum = []
        lbvalue = []
        lbcode = []
        plate_add_sign=True
        classified_data = {}
        #循环板块
        for it in value:
            #循环板块下个股
            StockList = it.get('StockList')
            ZSName = it.get('ZSName')
            num = it.get('num')
            ZSPop = it.get('ZSPop')
            if plate is not None and ZSName.find(plate) != -1 and plate_add_sign == True:
                plate_pop_data.append(ZSPop)
                plate_data.append(num)
                plate_add_sign = False

            for item in StockList:
                itemnum = item[7]
                itemvalue = item[1]
                itemcode = item[0]
                if itemvalue.find(Gv.ST) != -1:
                    continue
                if plate is not None and ZSName.find(plate) != -1:
                    if itemnum not in classified_data:
                        classified_data[itemnum] = []
                        # 将格式化后的字符串添加到对应分类的列表中
                    classified_data[itemnum].append(f"{itemvalue}")
                if itemnum>lbnum:
                    lbvalue.clear()
                    lbcode.clear()
                    lbvalue.append(itemvalue)
                    lbcode.append(itemcode)
                    lbnum = itemnum
                elif  itemnum == lbnum:
                    lbvalue.append(itemvalue)
                    lbcode.append(itemcode)
                secondnum.append(itemnum)
        if plate_add_sign != False:
            plate_pop_data.append(0)
            plate_data.append(0)
            plate_title_data.append({})
        else:
            plate_title_data.append(classified_data)
        title_data.append(lbvalue)
        code_data.append(lbcode)
        y_axis.append(lbnum)
        secondnumlen = len(secondnum)
        if secondnumlen==0:
            second_axis.append(0)
        elif secondnumlen == 1:
            second_axis.append(secondnum[1])
        else:
            sorted_numbers = sorted(secondnum, reverse=True)
            sorted_numbers_max = sorted_numbers[0]
            second_value = max(x for x in sorted_numbers if x < sorted_numbers_max)
            second_axis.append(second_value)

    #设置当天最高涨停
    if openstatus is not None and openstatus > 0:
        plate_data_all, result_time = xgbAPI.getUpDataFrame_char()
        now = datetime.now().strftime("%Y-%m-%d")
        if plate_data_all is not None and result_time == now:
            max_value = plate_data_all.iloc[:, 11].max()
            max_rows = plate_data_all[plate_data_all.iloc[:,11] == max_value]
            new_title_data_list = []
            new_code_data_list = []
            for index, row in max_rows.iterrows():
                new_title_data_list.append(row['股票名称'])
                new_code_data_list.append(row['股票代码'])
            x_axis.append(now)
            y_axis.append(max_value)
            title_data.append(new_title_data_list)
            code_data.append(new_code_data_list)
            plate_data.append(0)
            plate_title_data.append({})
            hread_data_obj.get('szjslist').append(0)
            hread_data_obj.get('xdjslist').append(0)
            plate_pop_data.append(0)
    result = {'x_axis':x_axis,'y_axis':y_axis,'title_data':title_data,'code_data':code_data,'hread_data':hread_data_obj,
              'plate_data':plate_data,'plate_title_data':plate_title_data,'plate_pop_data':plate_pop_data,'second_axis':second_axis}
    return  result


def js_code_handler(param,plate):
    title_data = param.get('title_data')
    code_data = param.get('code_data')
    plate_title_data = param.get('plate_title_data')
    plateList = []
    if plate is not None:
        plateList.append(plate)
    js_code_str = '''
                    function(params){
                        var index = params.dataIndex;
                        xdata = params.data[0];
                        var plateliststr = ''' + str(plateList) + ''';
                        if(xdata == null){
                          return '';
                        }

                        if (params.seriesName == '连扳高度'){
                            var z = ''' + str(title_data) + ''';
                            var zc = ''' + str(code_data) + ''';   
                            return
                             '<br/><div style="font-size: 20px;font-weight: bold;color:red;">' + params.seriesName + '</div>' +
                             '<br/><div style="font-size: 13px;font-weight: bold;">涨停时间：' + params.data[0] + '</div>' +
                             '<br/><div style="font-size: 13px;font-weight: bold;">连扳高度：' + params.data[1] + '连扳</div>' +
                             '<br/><div style="font-size: 13px;font-weight: bold;">股票代码：' + zc[index].join(',')+ '</div>' +
                             '<br/><div style="font-size: 13px;font-weight: bold;">股票名称：' + z[index].join(',')+ '</div>';
                        }else if(plateliststr.length > 0 && params.seriesName == plateliststr[0]){
                             var platejslist = ''' + str(plate_title_data) + ''';
                             var platejsindedxlist = platejslist[index];
                             let keys = Object.keys(platejsindedxlist);
                             keys.sort().reverse();
                             var result = '';
                             result += '<br/><div style="font-size: 20px;font-weight: bold;color:red;">' + params.seriesName + '</div>';
                             for(let key of keys){
                                let value = platejsindedxlist[key];
                                if(key == 1 && value.length>6){
                                    result += '<br/><div style="font-size: 13px;font-weight: bold;">首板：' + value.length + '</div>';
                                }else{
                                    result += '<br/><div style="font-size: 13px;font-weight: bold;">'+ key +'板：' + value.join(',') + '</div>';
                                }
                             }
                             return result;
                        }
                        else{
                            return '';
                        }

                    }
                    '''
    return js_code_str

def setLineChart(param,width,height,plate):
    x_axis = param.get('x_axis')
    y_axis = param.get('y_axis')
    title_data = param.get('title_data')
    code_data = param.get('code_data')
    hread_data = param.get('hread_data')
    plate_data = param.get('plate_data')
    plate_title_data = param.get('plate_title_data')
    plate_pop_data = param.get('plate_pop_data')
    #上涨下跌
    szjslist = hread_data.get('szjslist')
    xdjslist = hread_data.get('xdjslist')
    second_axis = param.get('second_axis')
    if x_axis is None or y_axis is None:
        return
    plateList = []
    if plate is not None:
        plateList.append(plate)
    js_code_str = js_code_handler(param,plate)
    line = (
        Line(init_opts = opts.InitOpts(chart_id='chart_111',width=str(width)+'px',height=str(height)+'px'))
        .add_xaxis(x_axis)
        .add_yaxis("连扳高度", y_axis,color='#87CEFA',
                   markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),#配置最大标记点
                   markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")],
                                                   linestyle_opts=opts.LineStyleOpts(color='orange',width=2)),#标记线配置
                   symbol="emptyCircle",symbol_size=10,#标记的图形
                   yaxis_index= 0,
                   )
        .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),
                         tooltip_opts=opts.TooltipOpts(formatter=JsCode(js_code_str)),
                         xaxis_opts=opts.AxisOpts(name=''),
                         yaxis_opts=opts.AxisOpts(name=''),
                         )
    )
    # 监听点击事件并绑定回调函数
    # 使用 add_js_funcs 方法绑定点击事件
    line.add_js_funcs('''
        chart_chart_111.on('click',function(params){
            var z = ''' + str(title_data) + ''';
            var zc = ''' + str(code_data) + ''';
            var index = params.dataIndex;
            xdata = params.data[0];
            if(xdata == null){
                return '';
            }
            if(params.seriesName != '连扳高度'){
               return '';
            }
            let xhr = new XMLHttpRequest();
            xhr.open('GET', 'http://localhost:8001/v1/scqx?codes='+zc[index].join(','));
            xhr.send();
            console.log(params.name);
        });
    ''')

    line_second = (
        Line()
        .add_xaxis(x_axis)
        .add_yaxis("次高度",second_axis,yaxis_index=0,color='orange')
        .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),legend_opts=opts.LegendOpts(selected_map={'次高度':False}))
    )
    line.extend_axis(yaxis=opts.AxisOpts(type_='value',name='涨跌',position='right'))
    line.overlap(line_second)
    line.render(fileaddr)

    line2 = (
        Line()
        .add_xaxis(x_axis)
        .add_yaxis("上涨数量",szjslist,yaxis_index=1,color='red')
        .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),legend_opts=opts.LegendOpts(selected_map={'上涨数量':False}))
    )
    line.extend_axis(yaxis=opts.AxisOpts(type_='value',name='涨跌',position='right'))
    line.overlap(line2)
    line.render(fileaddr)



    if plate is not None:
        line3 = (
            Line()
            .add_xaxis(x_axis)
            .add_yaxis(plate, plate_data, yaxis_index=2, color='purple',symbol_size = 8)
            .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),
                             legend_opts=opts.LegendOpts(selected_map={plate: False}),
                             tooltip_opts=opts.TooltipOpts(formatter=JsCode(js_code_str)),
                             )
        )
        line.extend_axis(yaxis=opts.AxisOpts(type_='value', name=plate, position='right',offset=30))
        line.overlap(line3)
        line.render(fileaddr)

        plate_pop = plate+'人气'
        line4 = (
            Line()
            .add_xaxis(x_axis)
            .add_yaxis(plate_pop, plate_pop_data, yaxis_index=3, color='purple',symbol_size = 8
                       ,linestyle_opts=opts.LineStyleOpts(type_='dashed'))
            .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),
                             legend_opts=opts.LegendOpts(selected_map={plate_pop: True}),
                             )
        )
        line.extend_axis(yaxis=opts.AxisOpts(type_='value', name=plate_pop, position='right',offset=60))
        line.overlap(line4)
        line.render(fileaddr)

    global line_global
    line_global = line

def appendlineHandler(param,width,height,plate):

    x_axis = param.get('x_axis')
    plate_data = param.get('plate_data')
    plate_pop_data = param.get('plate_pop_data')
    global line_global
    line = line_global
    if x_axis is None:
        return
    plateList = []
    if plate is not None:
        plateList.append(plate)
    js_code_str = js_code_handler(param, plate)
    global colorindex
    colorindex = colorindex % 10
    colorvalue = colorlist[colorindex]
    colorindex = colorindex + 1
    if plate is not None:
        line3 = (
            Line()
            .add_xaxis(x_axis)
            .add_yaxis(plate, plate_data, yaxis_index=2, color=colorvalue,symbol_size = 8)
            .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),
                             legend_opts=opts.LegendOpts(selected_map={plate: False}),
                             tooltip_opts=opts.TooltipOpts(formatter=JsCode(js_code_str)),
                             )
        )
        line.extend_axis(yaxis=opts.AxisOpts(type_='value', name=plate, position='right',offset=30))
        line.overlap(line3)
        line.render(fileaddr)

        plate_pop = plate+'人气'
        line4 = (
            Line()
            .add_xaxis(x_axis)
            .add_yaxis(plate_pop, plate_pop_data, yaxis_index=3, color=colorvalue,symbol_size = 8
                       ,linestyle_opts=opts.LineStyleOpts(type_='dashed'))
            .set_global_opts(title_opts=opts.TitleOpts(title="市场情绪"),
                             legend_opts=opts.LegendOpts(selected_map={plate_pop: True}),
                             )
        )
        line.extend_axis(yaxis=opts.AxisOpts(type_='value', name=plate_pop, position='right',offset=60))
        line.overlap(line4)
        line.render(fileaddr)

        line_global = line

def appendline(**kwargs):
    result = datahandler(numstr=kwargs.get('numstr'), plate=kwargs.get('plate'),openstatus=kwargs.get('openstatus'))
    appendlineHandler(result, kwargs.get('width'), kwargs.get('height'), kwargs.get('plate'))


def showLineChart(**kwargs):
    result = datahandler(numstr=kwargs.get('numstr'),plate=kwargs.get('plate'),plateischeck=kwargs.get('plateischeck'),openstatus=kwargs.get('openstatus'))
    setLineChart(result,kwargs.get('width'),kwargs.get('height'),kwargs.get('plate'))
# 解析 JSON 数据

def get_data():
    return 1,2
if __name__ == '__main__':
    #global colorindex
    colorindex = 6
    colorindex = colorindex % 10
    colorvalue = colorlist[colorindex]
    print(colorvalue)